package com.wondersgroup.rxjavatest;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.hss.rxjava.ApiManager;
import com.hss.rxjava.Constants;
import com.hss.rxjava.MD5;
import com.hss.rxjava.bean.HealthInfoModel;
import com.hss.rxjava.bean.Login;
import com.hss.rxjava.bean.ResultUserCashInfo;
import com.hss.rxjava.bean.UploadImageModel;
import com.hss.rxjava.bean.User;
import com.hss.rxjava.result.ResultListObject;
import com.hss.rxjava.result.ResultObject;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Subscriber;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class MainActivity extends AppCompatActivity {
    String userId, token;
    /**
     * 使用CompositeSubscription来持有所有的Subscriptions
     */
    protected CompositeSubscription mCompositeSubscription;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        mCompositeSubscription = new CompositeSubscription();

        InputStream ins = getApplicationContext().getResources().openRawResource(R.raw.serveryfytest);
        ApiManager.getInstance().init(ins, "111111");
        if (ins != null) {
            try {
                ins.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @OnClick({R.id.button, R.id.button2, R.id.button3, R.id.button4, R.id.button5, R.id.activity_main})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button:
                Subscription login = ApiManager.getInstance().getmApi().
                        login("13301668320", MD5.MD5add(MD5.MD5("111111").toLowerCase()).toLowerCase(), 1, 0).
                        subscribeOn(Schedulers.io()).
                        observeOn(AndroidSchedulers.mainThread()).
//                        map().
                        subscribe(new Subscriber<ResultObject<Login>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onNext(ResultObject<Login> loginResultObject) {
                                if (loginResultObject != null && loginResultObject.status == 1) {
                                    User userInfo = loginResultObject.getResponse().userInfo;
                                    userId = userInfo.userId;
                                    token = userInfo.getToken();

                                    ApiManager.getInstance().addHeader("token", userInfo.getToken());
                                    ApiManager.getInstance().addHeader("userId", userInfo.userId);

                                    Log.e("userInfo", new Gson().toJson(userInfo));
                                    Logger.e(new Gson().toJson(userInfo));

                                }
                            }
                        });

                break;
            case R.id.button2:
                Subscription userCashInfo = ApiManager.getInstance().getmApi().getUserCashInfo().
                        subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).
//                        map().
                        subscribe(new Subscriber<ResultObject<ResultUserCashInfo>>() {
                            @Override
                            public void onCompleted() {

                            }

                            @Override
                            public void onError(Throwable e) {
                                Logger.e(e.getMessage());
                                Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                            }

                            @Override
                            public void onNext(ResultObject<ResultUserCashInfo> resultUserCashInfoResultObject) {
                                if (resultUserCashInfoResultObject != null) {
                                    Log.e("healthInfoList", new Gson().toJson(resultUserCashInfoResultObject));
                                    Toast.makeText(getApplicationContext(), new Gson().toJson(resultUserCashInfoResultObject), Toast.LENGTH_SHORT).show();
                                }
                            }
                        });

                break;
            case R.id.button3:
                File img = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator + "06.jpg");
                RequestBody filebody = RequestBody.create(Constants.MEDIA_TYPE_STREAM, img);
                Subscription upteHeadIconCallBack = ApiManager.getInstance().getmApi().UpdataHeadIcon(filebody).
                        subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<ResultObject<UploadImageModel>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e.getMessage());
                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(ResultObject<UploadImageModel> uploadImageModelResultObject) {
                        if (uploadImageModelResultObject != null) {
                            Logger.e(new Gson().toJson(uploadImageModelResultObject));
                        }
                    }
                });

//                File img =new File(Environment.getExternalStorageDirectory().getPath()+File.separator+Environment.DIRECTORY_DOWNLOADS+File.separator+"04.jpg");
//                RequestBody filebody = RequestBody.create(Constants.MEDIA_TYPE_STREAM,img);
//                Call<ResultObject<UploadImageModel>>  upteHeadIconCallBack = ApiManager.getInstance().getmApi().UpdataHeadIcon(MultipartBody.Part.create(filebody) );
                break;
            case R.id.button4:
                //                reqParams.add("imageType", req.imagetype);
//                reqParams.add("applyType", req.applyType);
//                reqParams.add("groupId", req.groupId);
//                reqParams.add("flag", req.flag);
//                reqParams.add("applyId", req.applyId);
//                reqParams.add("caseId", req.caseId);
                MultipartBody.Builder reqBodyBuild = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM);
                reqBodyBuild.addFormDataPart("imageType", "医疗费用收据原件");
                reqBodyBuild.addFormDataPart("applyType", String.valueOf(1));
                reqBodyBuild.addFormDataPart("groupId", String.valueOf(100000501));
                reqBodyBuild.addFormDataPart("flag", String.valueOf(1));
                reqBodyBuild.addFormDataPart("applyId", "");
                reqBodyBuild.addFormDataPart("caseId", "864");

                File img1 = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator + "06.jpg");
                File img2 = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + Environment.DIRECTORY_DOWNLOADS + File.separator + "08.jpg");
                reqBodyBuild.addFormDataPart("files", "06.jpg", RequestBody.create(Constants.MEDIA_TYPE_IMG, img1));
                reqBodyBuild.addFormDataPart("files", "08.jpg", RequestBody.create(Constants.MEDIA_TYPE_IMG, img2));
                Subscription uploadImagesForClaimCallBack = ApiManager.getInstance().getmApi().uploadImagesForClaim(reqBodyBuild.build()).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<ResultObject<String>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e.getMessage());
                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(ResultObject<String> stringResultObject) {
                        if (stringResultObject != null) {
                            Log.e("healthInfoList", new Gson().toJson(stringResultObject));
                            Toast.makeText(getApplicationContext(), new Gson().toJson(stringResultObject), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                break;
            case R.id.button5:
                Subscription healthInfoList = ApiManager.getInstance().getmApi().getHealthInfoList(1, 10)
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<ResultListObject<HealthInfoModel>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.e(e.getMessage());
                        Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onNext(ResultListObject<HealthInfoModel> healthInfoModelResultListObject) {
                        if (healthInfoModelResultListObject != null) {
                            Log.e("healthInfoList", new Gson().toJson(healthInfoModelResultListObject));
                            Toast.makeText(getApplicationContext(), new Gson().toJson(healthInfoModelResultListObject), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //一旦调用了 CompositeSubscription.unsubscribe()，这个CompositeSubscription对象就不可用了,
        // 如果还想使用CompositeSubscription，就必须在创建一个新的对象了。
        mCompositeSubscription.unsubscribe();
    }
}
